package core;

import Utils.addUtils;
import Utils.tempWorkTree;
import fileoperation.FileCreation;
import fileoperation.FileReader;
import gitobject.Commit;
import gitobject.Tree;
import sha1.SHA1;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class JitStatus {
    public static void status() throws Exception {
        tempWorkTree.updateWorkTree();
        findBranch();
        checkLastCommit();
        boolean b = changesToBeCommit();
        boolean b1 = changesNotStaged();
        boolean b2 = filesUntracked();
        if((!b)&&(!b1)&&(!b2))
            nothingToCommit();
    }

    public static void findBranch() throws IOException {
        //On branch 
        File HEAD = new File(tempWorkTree.gitDir + File.separator + "HEAD");
        String branchName = Commit.getValue(HEAD).substring(16).replace("\n", "");
        System.out.println("On branch "+branchName);
    }

    public static void checkLastCommit() throws IOException {
        //没有提交过
        String lastCommit = Commit.getLastCommit();
        Commit commit=Commit.deserialize(lastCommit);
        if(commit==null)
            System.out.println("\nNo commits yet\n");
    }

    public static boolean changesToBeCommit() throws IOException {
        //3.changes to be committed：
        //  与上次commit不同且add的文件
        boolean tag=false;
        String lastIndex=null;
        StringBuilder stringBuilder=new StringBuilder();
        String path=tempWorkTree.indexLoc;
        List<String> curIndexs = addUtils.readIndex(path);
        String lastCommit = Commit.getLastCommit();
        Commit lcommit = Commit.deserialize(lastCommit);
        if(lcommit==null){
            lastIndex="";
            if(curIndexs.size()>=1){
                for (String curIndex : curIndexs) {
                    String filename=FileReader.readObjectKey(curIndex);
                    stringBuilder.append("\t\tnew file:\t"+filename+"\n");
                    tag=true;
                }
            }
        }        //  得到index文件和lastIndex文件，对比相同文件名的key，不一样，才可以commit
        
        else{
            Tree t=Tree.deserialize(lcommit.getTree());
            lastIndex= FileCreation.getlastIndex(t,tempWorkTree.workTree);
            ArrayList<String> lIndexs = FileReader.readByBufferReader(lastIndex);
            if(curIndexs.size()>=1){
                for (String curIndex : curIndexs) {
                    boolean existTag=false;
                    String filename=FileReader.readObjectKey(curIndex);
                    String key=FileReader.readObjectFileName(curIndex);
                    for (String lIndex : lIndexs) {
                        //先查询index中有无文件名，如果有此文件，查看key值，如果有变动，则是新修改的
                        if(filename.equals(FileReader.readObjectKey(lIndex))){
                            existTag=true;
                            if(!key.equals(FileReader.readObjectFileName(lIndex))){
                                stringBuilder.append("\t\tmodified:\t"+filename+"\n");
                                tag=true;
                            }
                        }
                    }
                    if(!existTag){
                        stringBuilder.append("\t\tnew file:\t"+filename+"\n");
                        tag=true;
                    }
                }
                if(tag){
                    System.out.println("Changes to be commited:");
                    System.out.println(stringBuilder);
                }
            }
        }
        return tag;
    }

    public static boolean changesNotStaged() throws Exception {
        //4.changes not staged for commit
        //add之后进行了修改的文件，diff分为deleted:  和  modified:
        boolean tag=false;
        tempWorkTree.updateWorkTree();
        StringBuilder stringBuilder = new StringBuilder();

        List<String> allLines = Files.readAllLines(Paths.get(tempWorkTree.indexLoc));
        for (String allLine : allLines) {//遍历index文件
            
            String fmt= FileReader.readObjectFmt(allLine);
            String key=FileReader.readObjectFileName(allLine);
            String path=FileReader.readObjectKey(allLine);

            File file=new File(path);

            if(!file.exists()){//文件已移除
                stringBuilder.append("\t\tdeleted:\t"+path);
                tag=true;
            }else if(!key.equals(SHA1.getHash(file)) ){
                stringBuilder.append("\t\tmodified:\t"+path);
                tag=true;
            }
        }
        if(tag){
            System.out.println("Changes not staged for commit:");
            System.out.println(stringBuilder);
        }
        return tag;
    }

    public static boolean filesUntracked() throws IOException {
        //5.遍历index文件
        StringBuilder stringBuilder = new StringBuilder();
        String curIndex=addUtils.readAllIndex(tempWorkTree.indexLoc);
        File dir = new File(tempWorkTree.workTree);
        File[] fs = dir.listFiles();
        for (File f : fs) {
            if(f.isFile()){
                searchUntrackedFile(f,stringBuilder,curIndex);
            }else if(!f.getName().equals(".jit")){
                searchUntrackedDir(f,stringBuilder,curIndex);
            }

        }
        if(stringBuilder.length()>=5){
            System.out.println("Untracked files:");
            System.out.println(stringBuilder);
        }
        boolean tag=stringBuilder.length()>=5?true:false;
        return tag;
    }
    public static void searchUntrackedFile(File file,StringBuilder stringBuilder,String index){
        if(!index.contains(file.getPath())){
            stringBuilder.append("\t\t"+file.getPath()+"\n");
        }
    }
    public static void searchUntrackedDir(File file,StringBuilder stringBuilder,String index){
        File[] files = file.listFiles();
        for (File file1 : files) {
            searchUntrackedFile(file1,stringBuilder,index);
        }
    }

    public static void nothingToCommit(){
        System.out.println("nothing to commit, working tree clean");
    }
}
